package com.herench.bs.core;

import com.herench.bs.support.TokenLifeCycle;
import com.herench.bs.utils.TokenUtils;
import org.springframework.util.Assert;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ThinkPad on 2017/8/14.
 */
public class TokenProvider {

    private static final ConcurrentHashMap<String, TokenLifeCycle> tokenCache = new ConcurrentHashMap();

    private static void addTokenCache(TokenLifeCycle tokenLifeCycle) {
        tokenCache.put(tokenLifeCycle.getTokenKey(), tokenLifeCycle);
    }

    public static TokenLifeCycle getTokenLifeCycle(String token) {
        return tokenCache.get(token);
    }

    public static TokenLifeCycle generatorToken(String username) {
        Assert.notNull(username, "username 不能为空.");
        String token = TokenUtils.generatorToken(username);
        TokenLifeCycle tokenLifeCycle = new TokenLifeCycle(token);
        addTokenCache(tokenLifeCycle);
        return tokenLifeCycle;
    }

    public static TokenLifeCycle refreshTokenLife(String token) {
        Assert.notNull(token, "token 不能为空.");
        TokenLifeCycle tokenLifeCycle = tokenCache.get(token);
        if (tokenLifeCycle == null) {
            throw new RuntimeException("token没有找到!");
        } else {
            tokenLifeCycle.refreshExpression();
        }
        return tokenLifeCycle;
    }


    public static boolean checkTokenLifeCycleIsLive(String token) {
        TokenLifeCycle tokenLifeCycle = tokenCache.get(token);
        return (tokenLifeCycle != null && tokenLifeCycle.isAlive());
    }


    public static void removeToken(String username) {
        Assert.notNull(username, "username 不能为空.");
        String token = TokenUtils.generatorToken(username);
        tokenCache.remove(token);
    }

    public static void checkTokenLifeCycleIsLiveByUsername(String username) {
        String token = TokenUtils.generatorToken(username);
        TokenLifeCycle tokenLifeCycle = tokenCache.get(token);
        if (tokenLifeCycle!=null && tokenLifeCycle.isAlive()){
                throw new RuntimeException("用户已经登录");
        }
    }
}
